package com.xuzy.x808.server.processor;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.xuzy.x808.common.enums.MsgTypeEnum;
import com.xuzy.x808.common.utils.SendUtils;
import com.xuzy.x808.entity.MsgHeader;
import com.xuzy.x808.entity.PackageData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 终端注册消息处理器
 */
@Component
public class ClientRegisterProcessor extends AbstractProcessor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void process(ChannelHandlerContext ctx, PackageData packageData) {
        MsgHeader msgHeader = packageData.getMsgHeader();

        //解析位置上报协议
        ByteBuf msgBody = packageData.getMsgBody();

        int provinceId = msgBody.readShort();
        int municipalId = msgBody.readShort();
        String producerId = StrUtil.str(ByteBufUtil.getBytes(msgBody.readBytes(5)), CharsetUtil.UTF_8).trim();
        String deviceModel = StrUtil.str(ByteBufUtil.getBytes(msgBody.readBytes(20)), CharsetUtil.UTF_8).trim();
        String deviceId = StrUtil.str(ByteBufUtil.getBytes(msgBody.readBytes(7)), CharsetUtil.UTF_8).trim();
        String licensePlateColor = StrUtil.str(msgBody.readByte(), CharsetUtil.GBK).trim();
        String licensePlateNumber = StrUtil.str(ByteBufUtil.getBytes(msgBody), CharsetUtil.GBK).trim();

        //回复0x8100
        response(ctx, msgHeader.getDevId(), MsgTypeEnum.CLIENT_REGISTER_RESP.getMsgId(), msgHeader.getSeq());
    }


    /**
     * @param devId 终端Id
     * @param msgId 应答消息Id
     * @param seq   应答流水号
     * @return
     */
    @Override
    public void response(ChannelHandlerContext ctx, String devId, Integer msgId, Integer seq) {
        ByteBuf msgBody = Unpooled.buffer();
        msgBody.writeShort(seq);
        msgBody.writeByte(0);
        msgBody.writeBytes("12345678".getBytes());
        ByteBuf response = SendUtils.packetNormalResponse(devId, msgId, msgBody);

        ctx.writeAndFlush(response);
    }
}
